"""
runner.py - A python program to determine page fault statistics using
output from ps calls.

Ben Marks, Chris Lekas
"""


from os import system


def getPIDInfo( pid ) :
    """
    Get information about a process, it's group, and the system.

    PID - process to get information about.
    """

    ## Get output of ps call
    cmd = "ps axo pid,ruid,min_flt,maj_flt > outfile"
    system( cmd )
    lines = open('outfile', 'r').readlines()
    lines = lines[1:]
    for i in range(len(lines)):
        lines[i] = lines[i].strip().split()

    # Initialize counters
    minor_pid = 0
    major_pid = 0

    # Figure out the UID of this PID
    uid = -1
    for line in lines :
        if line[0] == str(pid) :
            uid = int(line[1])
            minor_pid = int(line[2])
            major_pid = int(line[3])

    # Count information about the UID and System PF misses
    print uid
    minor_uid = 0
    major_uid = 0
    minor_sys = 0
    major_sys = 0

    for line in lines :
        #print line[2], line[3]
        if line[1] == str(uid) :
            minor_uid += int(line[2])
            major_uid += int(line[3])
        minor_sys += int(line[2])
        major_sys += int(line[3])

    ## Print results
    print "\n\nSystem Fault Information: "
    print "PID (", pid, "): "
    print "\tMinor Faults: ", minor_pid
    print "\tMajor Faults: ", major_pid
    print "UID (", uid, "): "
    print "\tMinor Faults: ", minor_uid
    print "\tMajor Faults: ", major_uid
    print "Entire System: "
    print "\tMinor Faults: ", minor_sys
    print "\tMajor Faults: ", major_sys


def askUser() :
    """
    Get the PID from the user. If the user wants info about all
    processes, then use init (pid = 1) as the pid. The system
    information is always printed, so the additional information
    is extraneous
    """
    flag = 0
    pid = input("Enter a PID, or -1 for all Pi's  ")
    
    if pid < 0 :
        return 1
    return pid


getPIDInfo( askUser() )

    
